<template>
  <div>
    <div class="search">
      <input v-model="keyword"
             class="inp"
             type="text"
             placeholder="请输出你要搜素的城市" />
      <button class="btn">搜索</button>
    </div>
    <div class="search-content"
         ref="search"
         v-show="keyword">
      <ul>
        <li class="search-item"
            v-for="item of list"
            :key="item"
            @click="handleCityClick(item.name)">
          {{ item.name }}
        </li>
        <li class="search-item"
            v-show="hasNoData">没有找到你搜索的城市</li>
      </ul>
    </div>
  </div>
</template>

<script>
import BScroll from "better-scroll";
import { mapState, mapMutations } from 'vuex'
export default {
  name: "citySearch",
  props: {
    cities: Object,
  },
  methods: {
    handleCityClick (city) {
      // this.$store.dispatch("changeCity", city);
      this.changeCity(city)
      this.keyword = "";
      this.$router.push("/");
    },
    ...mapMutations(["changeCity"]),
  },
  computed: {
    hasNoData () {
      return !this.list.length;
    },
  },
  data () {
    return {
      keyword: "",
      list: [],
      timer: null,
    };
  },
  watch: {
    keyword () {
      if (this.timer) {
        clearTimeout(this.timer);
      }
      if (!this.keyword) {
        this.list = [];
        return this.list;
      }
      this.timer = setTimeout(() => {
        const result = [];
        for (let i in this.cities) {
          this.cities[i].forEach((value) => {
            if (
              value.spell.indexOf(this.keyword) > -1 ||
              value.name.indexOf(this.keyword) > -1
            ) {
              result.push(value);
            }
          });
        }
        this.list = result;
      }, 100);
    },
  },
  mounted () {
    this.scroll = new BScroll(this.$refs.search, {
      observeDOM: true,
      click: true,
    });
  },
};
</script>

<style lang="stylus" scoped>
.search {
  height: 0.66rem;
  line-height: 0.66rem;
  background: #00bcd4;
  // padding-top:0.1rem
  padding-right: 0.2rem;
  padding-left: 0.2rem;
  position: relative;

  .inp {
    width: 80%;
    padding: 0 0.1rem;
    color: #666;
  }

  .btn {
    width: 15%;
    margin-left: 0.07rem;
  }
}

.search-content {
  overflow: hidden;
  position: absolute;
  top: 1.52rem;
  left: 0;
  right: 0;
  bottom: 0;
  background: #fff;
  z-index: 1;

  .search-item {
    line-height: 0.62rem;
    padding-left: 0.2rem;
    color: #666;
    border: 0.00002rem #ccc solid;
  }
}
</style>